#include "TextConverter.h"
#include <UTF.h>
#include <e32base.h>

TextConverter::TextConverter()
{
}

TextConverter::~TextConverter()
{
}

HBufC* TextConverter::ConvertUTF8ToUnicode(const TDesC8& aUTF8)
{
	const TInt segLen = 64;
	TBuf<segLen> tmpBuf;
	
	const TUint8* srcData = aUTF8.Ptr();
	TInt nSrcLen = aUTF8.Length();
	TPtrC8 ptrSrc(srcData,nSrcLen);
	TInt srcStartPos = 0;
	
	HBufC* pRetBuf = NULL;

	TInt retConvert = CnvUtfConverter::ConvertToUnicodeFromUtf8(tmpBuf,ptrSrc);
	while(retConvert != 0)
		{
		if(!pRetBuf)
			{
			pRetBuf = HBufC::NewL(tmpBuf.Length());
			CleanupStack::PushL(pRetBuf);
			TPtr ptrTemp = pRetBuf->Des();
			ptrTemp.Copy(tmpBuf);
			}
		else
			{
			CleanupStack::Pop(pRetBuf);
			TInt oldLen = pRetBuf->Length();
			pRetBuf = pRetBuf->ReAlloc(oldLen+tmpBuf.Length());
			CleanupStack::PushL(pRetBuf);
			TPtr ptrTemp = pRetBuf->Des();
			ptrTemp.Append(tmpBuf);
			}
		
		srcStartPos += nSrcLen-srcStartPos-retConvert;
		ptrSrc.Set(srcData+srcStartPos,retConvert);
		retConvert = CnvUtfConverter::ConvertToUnicodeFromUtf8(tmpBuf,ptrSrc);
		

		}
	
	if(retConvert == 0)
		{
		if(!pRetBuf && aUTF8.Length() != 0)
			{
			pRetBuf = HBufC::NewL(tmpBuf.Length());
			CleanupStack::PushL(pRetBuf);
			TPtr ptrTemp = pRetBuf->Des();
			ptrTemp.Copy(tmpBuf);
			}
		else if(pRetBuf)
			{
			CleanupStack::Pop(pRetBuf);
			TInt oldLen = pRetBuf->Length();
			pRetBuf = pRetBuf->ReAlloc(oldLen+tmpBuf.Length());
			CleanupStack::PushL(pRetBuf);
			TPtr ptrTemp = pRetBuf->Des();
			ptrTemp.Append(tmpBuf);
			}
		
		}
	
	
		
	
	if(pRetBuf)
		CleanupStack::Pop(1);
	
	return pRetBuf;
}